"use strict";
const electron = require("electron");
const { app, BrowserWindow, ipcMain } = require("electron");
const { exec } = require('child_process');
const fs = require('fs');
const os = require('os');
const si = require('systeminformation');
const path = require("path");

import { stderr, stdout } from 'process';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
import { listenOPSWindowEvents } from './windows/opsWindow';
import { listenFrontWindowEvents } from './windows/frontWindows';
import { listensupportWindowEvents } from './windows/supportWindows';

const configFilePath = path.join(app.getPath('userData'), 'store.json');
import { listenPropertyWindowEvents } from './windows/propertyWindow';  // wjh
let mainWindow;
let startBounds = { x: 0, y: 0 };
const isDevelopment = process.env.NODE_ENV !== "production";
const fixedWinSize = { width: 600, height: 400 };
function createWindow() {
  const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
  console.log(width, height);
  mainWindow = new BrowserWindow({
    width: fixedWinSize.width,
    height: fixedWinSize.height,
    webPreferences: {
      nodeIntegrationInWorker: true, // 是否在Web工作器中启用了Node集成
      nodeIntegration: true,
      contextIsolation: false, //Electron 12.0以上版本需要的额外设置此项
      enableRemoteModule: true,
      webSecurity: false,
    },
    transparent: true, // 设置窗口透明
    fullscreen: false,
    frame: false,
    resizable: false,
    backgroundColor: '#00000000',
  });

  if (isDevelopment) {
    mainWindow.loadURL("http://localhost:8080"); // 加载开发服务器上的页面
    mainWindow.webContents.openDevTools(); // 在开发模式下打开开发者工具
  } else {
    mainWindow.loadURL('app://./index.html');
  }

  mainWindow.on("closed", () => {
    mainWindow = null;
  });

  mainWindow.setMenuBarVisibility(false);
}

const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  app.quit(); // 如果无法获取锁，说明已有实例运行，退出当前进程
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当第二个实例启动时，激活（弹出）已打开的窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore(); // 如果最小化，恢复窗口
      mainWindow.focus(); // 聚焦窗口
    }
  });

  // 继续你的应用创建流程
  app.whenReady().then(() => {
    createWindow();
    listenOPSWindowEvents();
    listenFrontWindowEvents();
    listensupportWindowEvents();
    listenPropertyWindowEvents(); // 加入监听 // wjh
  });
}

/**
 * 启动程序，写入开机脚本至注册表
 */
if (process.platform == 'win32') {
  const appFolder = path.dirname(process.execPath);
  const vbsPathExe = path.resolve(appFolder, '..', 'xw_aiot/startup.vbs');
  // const vbsPathExe = '../startup.vbs';
  const exeName = path.basename(process.execPath);
  app.setLoginItemSettings({
    openAtLogin: true,
    path: vbsPathExe,
  });
}

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    try {
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString());
    }
  }
  createProtocol('app');
});

ipcMain.on('window-minimize', () => {
  mainWindow.minimize();
});

ipcMain.on('window-toggle-fullscreen', () => {
  mainWindow.setFullScreen(!mainWindow.isFullScreen());
});

ipcMain.on('window-close', () => {
  ipcMain.emit('broadcast-window-close');

  mainWindow.close();
});

// 读取当前 store 内容
function readStore() {
  if (fs.existsSync(configFilePath)) {
    try {
      const data = fs.readFileSync(configFilePath, 'utf-8');
      return JSON.parse(data);
    } catch (err) {
      console.error('读取配置文件失败:', err);
      return {};
    }
  }
  return {};
}

// 写入 store 内容
function writeStore(data) {
  try {
    fs.writeFileSync(configFilePath, JSON.stringify(data, null, 2), 'utf-8');
  } catch (err) {
    console.error('写入配置文件失败:', err);
  }
}

// 设置（新增或更新）键值
ipcMain.on('store-set', (event, key, value) => {
  const store = readStore();
  store[key] = value;
  writeStore(store);
  console.log(`设置成功: ${key} =`, value);
});

// 获取指定 key 的值
ipcMain.on('store-get', (event, key) => {
  const store = readStore();
  const value = store[key];
  event.returnValue = value !== undefined ? value : null;
  console.log(`读取 ${key}:`, value);
  event.sender.send('store-get-reply', { key, value });
});

// 删除指定 key
ipcMain.on('store-remove', (event, key) => {
  const store = readStore();
  if (key in store) {
    delete store[key];
    writeStore(store);
    console.log(`已删除: ${key}`);
  } else {
    console.log(`删除失败，${key} 不存在`);
  }
});


ipcMain.on('save-store', () => {
});

ipcMain.on('open-front', () => {
  mainWindow.webContents.send('open-front', true);
});

ipcMain.on('open-property-window', () => {
  mainWindow.webContents.send('open-property-window', true);
});

ipcMain.handle('open-local-tool', (event, appPath) => {
  // openLocalTool(appPath);
  runWelinkExe();
});

ipcMain.handle("get-static-path", () => {
  return `file://${path.join(app.getPath("exe"), "..", "resources")}/`;
});

function runWelinkExe() {
  const exePath = path.join(app.getPath("exe"), "..", "welink_V2.08.exe");

  exec(`"${exePath}"`, (error, stdout, stderr) => {
    if (error) {
      console.error(`执行出错: ${error.message}`);
      return;
    }
    console.log(`执行结果: ${stdout}`);
  });
}


function openLocalTool(appPath) {
  exec(appPath, (error, stdout, stderr) => {
    if (error) {
      console.log('exec error', error);
      return;
    }
    console.log('stdout', stdout);
    console.log('stderr', stderr);
  })
}

ipcMain.on('window-move-start', (event, { startX, startY }) => {
  if (mainWindow) {
    const bounds = mainWindow.getBounds();
    startBounds = {
      x: bounds.x,
      y: bounds.y,
      offsetX: startX - bounds.x || 0,
      offsetY: startY - bounds.y || 0
    };
  }
});

ipcMain.on('window-move', (event, { x, y }) => {
  if (mainWindow) {
    mainWindow.setBounds({
      x: x - startBounds.offsetX,
      y: y - startBounds.offsetY,
      width: fixedWinSize.width,
      height: fixedWinSize.height,
    });
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// ipcMain.handle('get-uuid', () => {
//   return new Promise((resolve, reject) => {
//     exec('wmic bios get serialnumber', (error, stdout, stdeer) => {
//       if (error) {
//         reject(`exec error: ${error}`);
//       }
//       if (stdeer) {
//         reject(`stderr: ${error}`);
//       }
//       resolve(stdout.trim());
//     })
//   })
// });

// ipcMain.handle('get-mac-address', () => {
//   const networkInterfaces = os.networkInterfaces();
//   let macAddress = null;
//   for (const iface in networkInterfaces) {
//     networkInterfaces[iface].forEach((address) => {
//       if (address.family === 'IPv4' && !address.internal) {
//         macAddress = address.mac;
//       }
//     });
//   }
//   return macAddress;
// });

ipcMain.handle('get-uuid', async () => {
  try {
    const data = await si.system();
    return data.uuid;
  } catch (error) {
    console.log('failed uuid', error);
    return error;
  }
});